//
//  PPFriendsViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/27/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPContactsFriendViewController.h"
#import "PPFoundViewController.h"

#import "PPContactsTableViewCell.h"

#import "PPContactsModel.h"
#import "PPNetworkService.h"
#import "PPProfileViewController.h"

static const NSInteger kCount = 50;

@interface PPContactsFriendViewController ()
@property (nonatomic, strong) NSNumber *next;
@end
@implementation PPContactsFriendViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRGBHex:0xf2f2f2];

    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"PPContactsTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveRelationshipChangedNotification:) name:PPRelationshipDidChangeNotification object:nil];
}

- (void)didReceiveRelationshipChangedNotification:(NSNotification *)notification {
    [self fetchNewItems];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    PPContactsModel *contacts = [self.items objectAtIndex:indexPath.row];

    if(contacts.avatar.length > 0) {
        NSString *url = [contacts.avatar hasPrefix:@"http:"] ? contacts.avatar : [NSString stringWithFormat:@"%@%@", contacts.avatarHost, contacts.avatar];
        [url applyToImageView:((PPContactsTableViewCell *)cell).avatarView];
    } else {
        ((PPContactsTableViewCell *)cell).avatarView.image = [UIImage imageNamed:@"icon-person-70"];
    }

    ((PPContactsTableViewCell *)cell).nickLabel.text = contacts.name;
    ((PPContactsTableViewCell *)cell).accountLabel.text = contacts.account;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    //进入个人主页
    [MobClick event:@"148"];
    PPContactsModel *user = [self.items safeObjectAtIndex:indexPath.row];
    PPProfileViewController *profileViewConroller = [[PPProfileViewController alloc] init];
    profileViewConroller.userID = user.userID;
    [self.navigationController pushViewController:profileViewConroller animated:YES];
}

#pragma mark - Timeline

- (NSArray *)initialItems {
    NSArray <PPContactsModel *> *localItems = [PPContactsModel where:@{@"currentUserID" : DGCurrentAccount.userID, @"relationship" : @1}];

    return localItems;
}

- (void)fetchNewItems {
    [super fetchNewItems];

    _next = nil;
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchFollowListWithTargetUserID:DGCurrentAccount.userID type:1 start:_next limit:kCount callback:^(id data, NSError *error) {
        if(data) {
            [weakSelf didReceiveNewResult:data];
        } else {
            [weakSelf didReceiveNewResult:error];
        }
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchFollowListWithTargetUserID:DGCurrentAccount.userID type:1 start:_next limit:kCount callback:^(id data, NSError *error) {
        if(data) {
            [weakSelf didReceiveMoreResult:data];
        } else {
            [weakSelf didReceiveMoreResult:error];
        }
    }];

}
- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    NSArray *users = [[result validDictionary] validArrayForKey:@"users"];
    [PPContactsModel performInBlock:^(NSManagedObjectContext *context) {
        [users enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {

            PPUserID userID = [[obj validDictionary] validStringForKey:@"user"];
            NSNumber *relationship = [[obj validDictionary] validNumberForKey:@"relationship"];
            PPContactsModel *contact = [PPContactsModel existingFanForUserID:userID relationShip:relationship];
            contact.name = [[obj validDictionary] validStringForKey:@"name"];
            contact.avatar = [[obj validDictionary] validStringForKey:@"avatar"];
            contact.signature = [[obj validDictionary] validStringForKey:@"signature"];
            contact.account = [obj validStringForKey:@"pickpic"];
            contact.avatarHost = [obj validStringForKey:@"avatarHost"];

            [items addSafeObject:contact];
        }];
        [context saveContext];
    }];

    return items;
}

- (void)clearItems {
    [PPContactsModel performInBlock:^(NSManagedObjectContext *context) {
        NSArray <PPContactsModel *> *localItems = [PPContactsModel where:@{@"currentUserID" : DGCurrentAccount.userID, @"relationship" : @1}];
        [localItems enumerateObjectsUsingBlock:^(PPContactsModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            [obj delete];
        }];
        [context saveContext];
    }];
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        DGAlignmentButton *button = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
        button.style = DGAlignmentButtonStyleImageTop;
        button.spacing = 10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        [button setImage:[UIImage imageNamed:@"icon-found-nothing"] forState:UIControlStateNormal];
        [button setTitle:@"去发现你感兴趣的人吧" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        [button sizeToFit];
        [button addTarget:self action:@selector(emptyPromptButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];

        return button;
    }
}

- (void)emptyPromptButtonDidPressed {
    [MobClick event:@"150"];
    PPFoundViewController *foundViewController = [[UIStoryboard storyboardWithName:@"Found" bundle:nil] instantiateViewControllerWithIdentifier:@"PPFoundViewController"];
    [self.navigationController pushViewController:foundViewController animated:YES];

}

- (UIEdgeInsets)preferredScrollInsets {
    return UIEdgeInsetsZero;
}

@end
